<?php

namespace app\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Issue;
use Yii;

/**
 * IssueSearch represents the model behind the search form of `app\models\Issue`.
 */
class IssueSearch extends Issue
{
    /** @var string 按联系人姓名搜索 */
    public $contactName;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id', 'projectId', 'contactId', 'priority', 'state'], 'integer'],
            [['name', 'detail', 'date', 'createdAt', 'updatedAt', 'contactName'], 'safe'],
        ];
    }

    public function attributeLabels(){
        return array_merge(['contactName' => Yii::t('app', 'Contact Name')], parent::attributeLabels());
    }

    /**
     * {@inheritdoc}
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Issue::find();        

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (! empty($this->contactName)) {
            $query->joinWith('contact');
        }

        if (!$this->validate()) {
            $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'projectId' => $this->projectId,
            'contactId' => $this->contactId,
            'priority' => $this->priority,
            'state' => $this->state,
            'date' => $this->date,
            'createdAt' => $this->createdAt,
            'updatedAt' => $this->updatedAt,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'detail', $this->detail])
            ->andFilterWhere(['like', 'contact.name', $this->contactName]);

        return $dataProvider;
    }
}
